package com.lkd.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.google.common.base.Strings;
import com.lkd.common.UserConstants;
import com.lkd.common.VMSystem;
import com.lkd.config.TopicConfig;
import com.lkd.contract.SupplyTaskContract;
import com.lkd.contract.TaskCompleteContract109;
import com.lkd.dao.TaskDao;
import com.lkd.dao.TaskDao2;
import com.lkd.emq.MqttProducer;
import com.lkd.entity.TaskDetailsEntity;
import com.lkd.entity.TaskEntity;
import com.lkd.entity.TaskStatusTypeEntity;
import com.lkd.exception.LogicException;
import com.lkd.feign.UserService;
import com.lkd.feign.VMService;
import com.lkd.http.vo.*;
import com.lkd.service.TaskDetailsService;
import com.lkd.service.TaskService;
import com.lkd.service.TaskStatusTypeService;
import com.lkd.vo.Pager;
import com.lkd.vo.UserVO;
import com.lkd.vo.VmVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

@Service
@Slf4j
public class TaskServiceImpl extends ServiceImpl<TaskDao,TaskEntity> implements TaskService{

    @Autowired
    private TaskStatusTypeService statusTypeService;

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @Autowired
    private VMService vmService;

    @Autowired
    private UserService userService;

    @Autowired
    private TaskDetailsService taskDetailsService;

    @Autowired
    private MqttProducer mqttProducer;

    @Autowired
    private TaskDao2 taskDao2;


    @Override
    public Pager<TaskEntity> search(Long pageIndex, Long pageSize, String innerCode, Integer userId, String taskCode, Integer status, Boolean isRepair, String start, String end) {
        Page<TaskEntity> page = new Page<>(pageIndex,pageSize);
        LambdaQueryWrapper<TaskEntity> qw = new LambdaQueryWrapper<>();
        if(!Strings.isNullOrEmpty(innerCode)){
            qw.eq(TaskEntity::getInnerCode,innerCode);
        }
        if(userId != null && userId > 0){
            qw.eq(TaskEntity::getUserId,userId);
        }
        if(!Strings.isNullOrEmpty(taskCode)){
            qw.like(TaskEntity::getTaskCode,taskCode);
        }
        if(status != null && status > 0){
            qw.eq(TaskEntity::getTaskStatus,status);
        }
        if(isRepair != null){
            if(isRepair){
                qw.ne(TaskEntity::getProductTypeId, VMSystem.TASK_TYPE_SUPPLY);
            }else {
                qw.eq(TaskEntity::getProductTypeId,VMSystem.TASK_TYPE_SUPPLY);
            }
        }
        if(!Strings.isNullOrEmpty(start) && !Strings.isNullOrEmpty(end)){
            qw
                    .ge(TaskEntity::getCreateTime, LocalDate.parse(start, DateTimeFormatter.ISO_LOCAL_DATE))
                    .le(TaskEntity::getCreateTime,LocalDate.parse(end,DateTimeFormatter.ISO_LOCAL_DATE));
        }
        //根据最后更新时间倒序排序
        qw.orderByDesc(TaskEntity::getUpdateTime);

        return Pager.build(this.page(page,qw));
    }



    @Override
    public List<TaskStatusTypeEntity> getAllStatus() {
        QueryWrapper<TaskStatusTypeEntity> qw = new QueryWrapper<>();
        qw.lambda()
                .ge(TaskStatusTypeEntity::getStatusId,VMSystem.TASK_STATUS_CREATE);

        return statusTypeService.list(qw);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean create(TaskViewModel taskViewModel) {

        //1.校验是否存在同样类型的工单
        boolean exist = hasTask(taskViewModel.getInnerCode(),taskViewModel.getProductType());
        if(exist){
            throw new LogicException("同类型工单已经存在!");
        }
        //2.校验售货机状态是否和工单类型匹配
        VmVO vmInfo = vmService.getVMInfo(taskViewModel.getInnerCode());
        if(vmInfo == null){
            throw new LogicException("售货机不存在");
        }
        checkVmStatusAndProductionType(vmInfo.getVmStatus(),taskViewModel.getProductType());

        UserVO user = userService.getUser(taskViewModel.getUserId());
        if(user == null){
            throw new LogicException("用户不存在");
        }


        //3.创建主表数据
        TaskEntity taskEntity = new TaskEntity();
        BeanUtils.copyProperties(taskViewModel,taskEntity);
        //工单状态
        taskEntity.setTaskStatus(VMSystem.TASK_STATUS_CREATE);
        //用户名
        taskEntity.setUserName(user.getUserName());
        //区域id
        taskEntity.setRegionId(vmInfo.getRegionId());
        //工单类型
        taskEntity.setProductTypeId(taskViewModel.getProductType());
        //设置编号
        taskEntity.setTaskCode(generateTaskCode());
        //设置地址
        taskEntity.setAddr(vmInfo.getNodeAddr());
        save(taskEntity); //保存数据库之后回写主键id

        //4.如果是补货工单，添加详情数据到详情表中
        if(Objects.equals(taskViewModel.getProductType(),VMSystem.TASK_TYPE_SUPPLY)){
//            for (TaskDetailsViewModel detail : taskViewModel.getDetails()) {
//                TaskDetailsEntity taskDetailsEntity = new TaskDetailsEntity();
//                BeanUtils.copyProperties(detail,taskDetailsEntity);
//                taskDetailsEntity.setTaskId(taskEntity.getTaskId()); //关联主表
//                taskDetailsService.save(taskDetailsEntity);
//            }

            List<TaskDetailsViewModel> details = taskViewModel.getDetails();
            if(CollectionUtils.isNotEmpty(details)){

                List<TaskDetailsEntity> list = details.stream().map(x -> {
                    TaskDetailsEntity taskDetailsEntity = new TaskDetailsEntity();
                    BeanUtils.copyProperties(x, taskDetailsEntity);
                    taskDetailsEntity.setTaskId(taskEntity.getTaskId()); //关联主表
                    return taskDetailsEntity;
                }).collect(Collectors.toList());

                taskDetailsService.saveBatch(list);
            }


        }

        //给工单数 + 1
        redisTemplate.opsForZSet().incrementScore(VMSystem.REGION_TASK_KEY_PREF
                + user.getRegionId()
                + user.getRoleCode(),taskViewModel.getUserId(),1.0);
        return true;
    }

    @Override
    public boolean accept(TaskEntity task) {

        if(!Objects.equals(task.getTaskStatus(),VMSystem.TASK_STATUS_CREATE)){
            throw new LogicException("工单状态不是待处理!");
        }

        //修改状态为处理中
        task.setTaskStatus(VMSystem.TASK_STATUS_PROGRESS);

        return updateById(task);
    }

    @Override
    public boolean cancel(TaskEntity task) {

        if(Objects.equals(task.getTaskStatus(),VMSystem.TASK_STATUS_CANCEL)
            || Objects.equals(task.getTaskStatus(),VMSystem.TASK_STATUS_FINISH)
        ){
            throw new LogicException("工单已经完成或者被取消!");
        }
        task.setTaskStatus(VMSystem.TASK_STATUS_CANCEL);

        UserVO user = userService.getUser(task.getUserId());
        if(user == null){
            throw new LogicException("用户不存在");
        }

        //给工单数 - 1
        redisTemplate.opsForZSet().incrementScore(VMSystem.REGION_TASK_KEY_PREF
                + user.getRegionId()
                + user.getRoleCode(),user.getUserId(),-1.0);

        return updateById(task);
    }

    @Override
    public boolean complete(TaskEntity task) {

        if(Objects.equals(task.getTaskStatus(),VMSystem.TASK_STATUS_CANCEL)
                || Objects.equals(task.getTaskStatus(),VMSystem.TASK_STATUS_FINISH)
        ){
            throw new LogicException("工单已经完成或者被取消!");
        }

        UserVO user = userService.getUser(task.getUserId());
        if(user == null){
            throw new LogicException("用户不存在");
        }

        //修改状态为处理中
        task.setTaskStatus(VMSystem.TASK_STATUS_FINISH);

        if(Objects.equals(task.getProductTypeId(),VMSystem.TASK_TYPE_DEPLOY)
            ||  Objects.equals(task.getProductTypeId(),VMSystem.TASK_TYPE_REVOKE)
        ){
            //发送消息 投放/撤机 售货机编码
            notifyDeployAndRevokeMsg(task);

        }else if(Objects.equals(task.getProductTypeId(),VMSystem.TASK_TYPE_SUPPLY)){
            //补货工单
            notifySupplyTaskMsg(task);
        }

        //给工单数 - 1
        redisTemplate.opsForZSet().incrementScore(VMSystem.REGION_TASK_KEY_PREF
                + user.getRegionId()
                + user.getRoleCode(),user.getUserId(),-1.0);

        return updateById(task);
    }

    @Override
    public Integer getLeastTaskUser(Long regionId, boolean isRepair) {

        Set<Object> range = redisTemplate.opsForZSet().range(VMSystem.REGION_TASK_KEY_PREF
                + regionId
                + (isRepair ? UserConstants.ROLE_CODE_REPAIR : UserConstants.ROLE_CODE_OPERATION),
                0, 0);
        if(CollectionUtils.isEmpty(range)){
            return null;
        }

        return (Integer) new ArrayList<>(range).get(0);
    }

    @Override
    public List<TaskReportInfoVO> taskReportInfo(LocalDateTime start, LocalDateTime end) {

        List<TaskReportInfoVO> taskReportInfoVOS = new ArrayList<>();

        //1.运营人员
        TaskReportInfoVO taskReportInfoVO = new TaskReportInfoVO();
        taskReportInfoVO.setRepair(false); //是否运维人员
        taskReportInfoVO.setWorkerCount(userService.getOperatorCount()); //获取运营人员数量
        taskReportInfoVO.setTotal(countTask(null,start,end,false));
        taskReportInfoVO.setCompletedTotal(countTask(VMSystem.TASK_STATUS_FINISH,start,end,false));
        taskReportInfoVO.setCancelTotal(countTask(VMSystem.TASK_STATUS_CANCEL,start,end,false));
        taskReportInfoVO.setProgressTotal(countTask(VMSystem.TASK_STATUS_PROGRESS,start,end,false));
        taskReportInfoVOS.add(taskReportInfoVO);

        //2.运维人员
        TaskReportInfoVO taskReportInfoVO2 = new TaskReportInfoVO();
        taskReportInfoVO2.setRepair(true); //是否运维人员
        taskReportInfoVO2.setWorkerCount(userService.getRepairerCount()); //获取运维人员数量
        taskReportInfoVO2.setTotal(countTask(null,start,end,true));
        taskReportInfoVO2.setCompletedTotal(countTask(VMSystem.TASK_STATUS_FINISH,start,end,true));
        taskReportInfoVO2.setCancelTotal(countTask(VMSystem.TASK_STATUS_CANCEL,start,end,true));
        taskReportInfoVO2.setProgressTotal(countTask(VMSystem.TASK_STATUS_PROGRESS,start,end,true));
        taskReportInfoVOS.add(taskReportInfoVO2);

        return taskReportInfoVOS;
    }

    @Override
    public List<UserWorkTopVO> userWorkTop10(LocalDate start, LocalDate end, boolean isRepair, long regionId) {

        Page<UserWorkTopVO> page = new Page<>();
        page.setCurrent(1);
        page.setSize(10);
        page.setSearchCount(false);  //分页 1.查询这一页数据 2.查询总数据 totalCount 把totalCount禁用

        return taskDao2.userWorkTop10(page,start,end.plusDays(1),isRepair,regionId);
    }

    @Override
    public List<CollectTaskVo> collectReport(LocalDate startDate, LocalDate endDate) {

        List<CollectTaskVo> collectTaskVos = new ArrayList<>();

        //18  20
        startDate.datesUntil(endDate.plusDays(1), Period.ofDays(1))
                .forEach(date -> {
                    //获取到date这一天日期
                    CollectTaskVo collectTaskVo = new CollectTaskVo();
                    collectTaskVos.add(collectTaskVo);
                    collectTaskVo.setCollectDate(date.format(DateTimeFormatter.ISO_LOCAL_DATE));
                    collectTaskVo.setProgressCount(countTask(VMSystem.TASK_STATUS_PROGRESS,date,date.plusDays(1)));
                    collectTaskVo.setFinishCount(countTask(VMSystem.TASK_STATUS_FINISH,date,date.plusDays(1)));
                    collectTaskVo.setCancelCount(countTask(VMSystem.TASK_STATUS_CANCEL,date,date.plusDays(1)));

                });
        return collectTaskVos;
    }

    private int countTask(Integer status, LocalDate start, LocalDate end) {

        LambdaQueryWrapper<TaskEntity> queryWrapper = Wrappers.<TaskEntity>lambdaQuery();
        //1.加入开始和结束时间
        queryWrapper.ge(TaskEntity::getUpdateTime,start); //>=开始日期
        queryWrapper.lt(TaskEntity::getUpdateTime,end); //<结束日期
        //2.判断状态
        if (status != null) {
            queryWrapper.eq(TaskEntity::getTaskStatus, status);
        }

        return count(queryWrapper);
    }

    private int countTask(Integer status, LocalDateTime start, LocalDateTime end, boolean isRepair) {

        LambdaQueryWrapper<TaskEntity> queryWrapper = Wrappers.<TaskEntity>lambdaQuery();
        //1.加入开始和结束时间
        queryWrapper.between(TaskEntity::getUpdateTime,start,end);
        //2.判断状态
        if(status != null){
            queryWrapper.eq(TaskEntity::getTaskStatus,status);
        }
        //3.判断运维还是运营工单 运维工单 != 2  运营工单 = 2
        if(isRepair){
            queryWrapper.ne(TaskEntity::getProductTypeId,VMSystem.TASK_TYPE_SUPPLY);
        }else{
            queryWrapper.eq(TaskEntity::getProductTypeId,VMSystem.TASK_TYPE_SUPPLY);
        }

        return count(queryWrapper);
    }


    private void notifySupplyTaskMsg(TaskEntity task) {
        SupplyTaskContract supplyTaskContract = new SupplyTaskContract();
        supplyTaskContract.setInnerCode(task.getInnerCode());

        //查询详情数据
        List<TaskDetailsEntity> list = taskDetailsService.list(Wrappers.<TaskDetailsEntity>lambdaQuery()
                .eq(TaskDetailsEntity::getTaskId, task.getTaskId())
        );
        List<SupplyTaskContract.SupplyTaskChannel> collect = list.stream().map(x -> {
            SupplyTaskContract.SupplyTaskChannel supplyTaskChannel =
                    new SupplyTaskContract.SupplyTaskChannel();
            supplyTaskChannel.setChannelCode(x.getChannelCode());
            supplyTaskChannel.setCapacity(x.getExpectCapacity());
            return supplyTaskChannel;
        }).collect(Collectors.toList());
        supplyTaskContract.setChannelList(collect);

        try {
            mqttProducer.send(TopicConfig.VMS_SUPPLY_TOPIC,1,supplyTaskContract);
        } catch (JsonProcessingException e) {
            log.error("json转换出错",e);
            throw new LogicException("json转换出错");
        }
    }

    private void notifyDeployAndRevokeMsg(TaskEntity task) {
        TaskCompleteContract109 contract = new TaskCompleteContract109();
        contract.setInnerCode(task.getInnerCode());
        contract.setType(task.getProductTypeId().equals(VMSystem.TASK_TYPE_DEPLOY)?
                        TaskCompleteContract109.TaskCompleteContractType.DEPLOY
                        : TaskCompleteContract109.TaskCompleteContractType.REVOKE
                );
        try {
            mqttProducer.send(TopicConfig.VMS_COMPLETED_TOPIC,1,contract);
        } catch (JsonProcessingException e) {
            log.error("json转换出错",e);
            throw new LogicException("json转换出错");
        }
    }

    private void checkVmStatusAndProductionType(Integer vmStatus, int productType) {
        //（1）如果是投放工单，状态为运营，抛出异常
        if(productType == VMSystem.TASK_TYPE_DEPLOY &&
                Objects.equals(vmStatus,VMSystem.VM_STATUS_RUNNING)){
            throw new LogicException("该设备已运营");
        }
        //（2）如果是补货工单，状态不是运营状态，抛出异常
        if(productType == VMSystem.TASK_TYPE_SUPPLY &&
                !Objects.equals(vmStatus,VMSystem.VM_STATUS_RUNNING)){
            throw new LogicException("该设备不在运营状态");
        }
        //（3）如果是撤机工单，状态不是运营状态，抛出异常
        if(productType == VMSystem.TASK_TYPE_REVOKE &&
                !Objects.equals(vmStatus,VMSystem.VM_STATUS_RUNNING)){
            throw new LogicException("该设备不在运营状态");
        }

//        // (4) 如果是维修工单，不是运营中抛出异常
//        if(productType == VMSystem.TASK_TYPE_REPAIR &&
//                !Objects.equals(vmStatus,VMSystem.VM_STATUS_RUNNING)){
//            throw new LogicException("该设备不在运营状态");
//        }
    }

    private boolean hasTask(String innerCode, int productType) {
        int count = count(Wrappers.<TaskEntity>lambdaQuery()
                .eq(TaskEntity::getInnerCode, innerCode)
                .eq(TaskEntity::getProductTypeId, productType)
                .le(TaskEntity::getTaskStatus, VMSystem.TASK_STATUS_PROGRESS) //<=2  1,2
                .select(TaskEntity::getTaskId)
        );
        return count > 0;
    }


    /**
     * 生成工单编号
     * @return
     */
    private String generateTaskCode(){
        //日期+序号
        String date = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));  //日期字符串 202212020002
        String key= "lkd.task.code."+date; //redis key
        Object obj = redisTemplate.opsForValue().get(key);
        if(obj==null){
            redisTemplate.opsForValue().set(key,1L, Duration.ofDays(1) );
            return date+"0001"; //202212010001
        }
        return date+  Strings.padStart( redisTemplate.opsForValue().increment(key,1).toString(),4,'0');
    }

    public static void main(String[] args) {
        String s = Strings.padStart("123", 4, '0');
        System.out.println(s);

        LocalDate localDate = LocalDate.now().minusDays(5);
        LocalDate now = LocalDate.now();

        List<LocalDate> dates =
                localDate.datesUntil(now.plusDays(1),Period.ofDays(1)).collect(Collectors.toList());

        System.out.println(dates);

        Integer i = 6;
        int t = 6;
        System.out.println(i.equals(t));
    }


}
